const Minio = require("minio");
const stream = require("stream");
// minio上传文件
const minioClient = new Minio.Client({
  endPoint: "smallpig.site",
  port: 9000,
  useSSL: true,
  rootUser: "lanyuan",
  rootPassword: "20153106l",
});

// 上传文件方法
function pfupload(fileObj, callback) {
  if (fileObj) {
    let file = fileObj;
    //判断是否选择了文件
    if (file == undefined) {
      //未选择
      console.log("请上传文件");
    } else {
      //获取文件类型及大小
      const fileName = file.name;
      const mineType = file.type;
      const fileSize = file.size;

      //参数
      let metadata = {
        "content-type": mineType,
        "content-length": fileSize,
      };

      //判断储存桶是否存在
      minioClient.bucketExists("navigation", function (err) {
        if (err) {
          if (err.code == "NoSuchBucket") {
            return console.log("bucket does not exist.");
          }
          return console.log(err);
        }
        //存在
        console.log("Bucket exists.");

        //准备上传
        let fr = new FileReader(); //用FileReader 读取文件流
        fr.readAsArrayBuffer(file);
        fr.onload = function (e) {
          //定义流
          let bufferStream = new stream.PassThrough();
          //将buffer写入
          bufferStream.end(Buffer.from(e.target.result));
          //上传F
          minioClient.putObject(
            "navigation",
            fileName,
            bufferStream,
            fileSize,
            metadata,
            function (err, etag) {
              if (err) {
                callback(null);
              } else {
                let responseData = {
                  fileName: fileName,
                  fileUrl: "https://smallpig.site:9000/navigation/" + fileName,
                  fileSize: fileSize,
                };
                callback(responseData);
              }
            }
          );
        };
      });
    }
  }
}
export { pfupload };
